import { getApiClient } from '../utils/api';
export function useArticleDetail(articleId) {
  console.log("进来了进来了-------------"+articleId)

// 确保接收响应式引用
  const idRef = computed(() => {
    const id = unref(articleId);
    return id?.toString() || '0';
  });
  // 生成唯一且类型安全的key
  const getDataKey = computed(() => `article-${idRef.value}`);
  const state = reactive({
    article: {
      articleTitle: '',
      createTime: null,
      author: {
        avatar: '',
        nickName: '',
      },
      articleTags: '',
      articleViewCount: 0,
      articleGoodCnt: 0,
      articleCommentCount: 0,
      articleCollectCnt: 0,
      articleContent: ''
    },
    error: null,
    loading: true
  });

  const relatedArticles = ref([]);
  const relatedData = ref([]);
  const { data, refresh } = useAsyncData(
      getDataKey.value,
      async () => {
        try {
          const response = await getApiClient().get(`/app/article/${idRef.value}`);
          if (response.code === 200) return response.data;
          // 主动抛出可识别错误
          throw createError({
            statusCode: response.code === 404 ? 404 : 500,
            message: response.message
          });
        } catch (error) {
          // 统一错误处理
          if (error.statusCode) throw error; // 传递已有错误
          throw createError({ statusCode: 500, message: '服务器错误' });
        }
      },
      { server: true, lazy: false, watch: [idRef] }
  );




  // 相关文章数据获取
  /*const { data: relatedData } = useAsyncData(
      `related/${idRef.value}`,
      async () => {
        try {
          const response = await getApiClient().get(`/app/article/related/${idRef.value}`);
          return response.data?.list || [];
        } catch (error) {
          console.error('相关文章加载失败:', error);
          return [];
        }
      },
      {
        watch: [idRef],
        server: true
      }
  );*/

  return {
    article :data?data:state.article,
    relatedArticles: computed(() => relatedArticles.value),
    refresh
  };
}
